import React, { Component } from 'react';
import {
  StyleSheet, Text, View, TextInput, ScrollView, TouchableOpacity, DeviceEventEmitter, Alert, Image, TouchableWithoutFeedback,
} from 'react-native';
import { Icon } from 'native-base';
import produce from 'immer';
import DeviceInfo from 'react-native-device-info';
import ImagePicker from 'react-native-image-crop-picker';
import theme from '../../../native-base-theme/variables';
import ZlstIcon from '../../../components/zlst-icons';
import { ipConfig } from '../../../services/config';
import * as inspectionService from '../../../services/inspection';
import * as todoService from '../../../services/todo';
import { UtilToast, getCurrentPosition } from '../../../utils/util-method';

import {
  FormText, FormButtonRadio, FormTitle, FormButtonChoice,
  FormTextarea, FormTakephoto, FormSearchChoice, FormInput,
} from '../../../components';

class AddTaskDevice extends Component {
  static navigationOptions = {
    title: '巡检设备',
    headerStyle: { backgroundColor: theme.toolbarDefaultBg, borderBottomWidth: 0, elevation: 0 },
    headerTintColor: '#FFFFFF',
    headerBackTitle: null,
    headerTruncatedBackTitle: '返回',
    headerTitleStyle: {
      fontWeight: 'bold',
      fontSize: 20,
      flex: 1,
      textAlign: 'center',
    },
    headerBackImage: (
      <ZlstIcon
        name="fanhui"
        size={24}
        color="white"
      />
    ),
    headerRight: <View />,
  }

  failurePic = '';

  constructor(props) {
    super(props);
    this.state = {
      // inspectItems: [{
      //   checkWay: [],
      //   inspection: '无弯曲无变形',
      //   inspectionType: '',
      //   normalLowerLimit: '',
      //   normalUpperLimit: '',
      //   objType: '',
      //   resultItemsDic: '',
      //   resultItemsDicitem: '',
      //   resultType: '0',
      //   splitItemDescription: '大梁',
      //   splitItemId: '',
      //   spotId: '',
      //   warmLowerLimit: '',
      //   warmUpperLimit: '',
      //   checked: true,
      //   desc: '',
      // }, {
      //   checkWay: [],
      //   inspection: 'value',
      //   inspectionType: '',
      //   normalLowerLimit: '',
      //   normalUpperLimit: '',
      //   objType: '',
      //   resultItemsDic: '',
      //   resultItemsDicitem: '',
      //   resultType: '2',
      //   splitItemDescription: '表面温度',
      //   splitItemId: '',
      //   spotId: '',
      //   warmLowerLimit: '',
      //   warmUpperLimit: '',
      //   checked: true,
      //   desc: '',
      // }],
      inspectItems: [],
      equipmentName: '',
      equipmentId: '',
      equipmentCode: '',
      choiceAll: true,
      inpectResult: [{ name: '正常', checked: true, value: '1' }, { name: '异常不影响运行', checked: false, value: '2' }, { name: '异常', checked: false, value: '0' }],
      remark: '',
      images: [],
    };
  }

  componentDidMount() {
    this.getDeviceInspectInfo();
  }

  componentWillUnmount() {
    ImagePicker.clean().then(() => {
      console.log('removed all tmp images from tmp directory');
    }).catch(e => {
      console.log(e);
    });
  }

  // saveInfoEvent = () => {
  //   Alert.alert(
  //     '提示',
  //     '退出需要保存草稿吗',
  //     [
  //       {
  //         text: '不保存',
  //         style: 'cancel',
  //         onPress: () => {
  //           if (this.failureId) {
  //             this.delDraft(true, this.failureId);
  //           } else {
  //             this.props.navigation.goBack();
  //           }
  //         },
  //       },
  //       {
  //         text: '保存',
  //         onPress: () => {
  //           this.confirmSub('01');
  //         },
  //       },
  //     ],
  //   );
  // }

  // 获取设备巡检信息
  getDeviceInspectInfo = async () => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const { code } = this.props.navigation.state.params;
      const { data, equipmentName, equipmentId } = await inspectionService.findByEquipmentCode({ equipmentCode: code });
      if (data) {
        DeviceEventEmitter.emit('showLoading', false);
        this.setState({ inspectItems: data, equipmentName, equipmentId, equipmentCode: code });
      } else {
        DeviceEventEmitter.emit('showLoading', false);
      }
    } catch (e) {
      console.log(e);
      DeviceEventEmitter.emit('showLoading', false);
      this.props.navigation.goBack();
    }
  }

  addImage = (uri) => {
    this.setState(produce(draft => {
      draft.images.push(uri);
      // draft.images = [uri];
    }));
  }

  delImage = (index) => {
    Alert.alert(
      '提示',
      '确定删除照片',
      [
        {
          text: '取消',
          style: 'cancel',
        },
        {
          text: '确定',
          onPress: () => {
            this.setState(produce(draft => {
              draft.images.splice(index, 1);
            }));
          },
        },
      ],
    );
  }

  showBigImage = () => {
    DeviceEventEmitter.emit('showBigImage', { show: true, url: this.state.images[0].uri });
  }

  confirmSub = async () => {
    // if (sbid === '') {
    //   UtilToast('请选择设备信息', 'danger');
    // } else {
    Alert.alert(
      '提示',
      '确定提交',
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          onPress: () => {
            // this.submit();
            this.check();
          },
        },
      ],
    );
    // }
  }

  inpectResult = (v) => {
    const inpectResult = this.state.inpectResult.map(it => ({
      ...it,
      checked: it.name === v.name,
    }));

    this.setState(produce(draft => {
      draft.inpectResult = inpectResult;
    }));
  }

  check = () => {
    let mdata;
    for (let i = 0; i < this.state.inspectItems.length; i++) {
      const data = this.state.inspectItems[i];
      if (data.choice && data.resultType == '2') {
        if (!data.desc) {
          mdata = data;
          break;
        }
      }
    }
    if (!mdata) {
      this.submit();
    } else {
      UtilToast(`请填写巡检项‘${mdata.splitItemDescription}’`, 'danger');
    }
  }

  submit = async () => {
    DeviceEventEmitter.emit('showLoading', true);
    try {
      const emsEcmCheckImages = [];
      if (this.state.images.length > 0) {
        const imagesInfo = await todoService.uploadPics(this.state.images);
        const images = imagesInfo.data;
        images.forEach((data, index) => {
          emsEcmCheckImages.push({ imageOrder: index, imagePath: data.fileId });
        });
      }
      const emsEcmSpotRecords = [];
      this.state.inspectItems.forEach(data => {
        if (data.choice) {
          let result = '1';
          let resultDesc = data.desc;
          if (data.resultType == '0') {
            result = data.checked ? '1' : '0';
          } else if (data.resultType == '2') {
            if (data.desc) {
              if (data.normalLowerLimit != null && data.normalUpperLimit != null) {
                result = data.desc >= data.normalLowerLimit && data.desc <= data.normalUpperLimit ? '1' : '0';
              } else if (data.normalLowerLimit != null) {
                result = data.desc >= data.normalLowerLimit ? '1' : '0';
              } else if (data.normalUpperLimit != null) {
                result = data.desc <= data.normalUpperLimit ? '1' : '0';
              } else {
                result = '1';
              }
            } else {
              result = '1';
            }
            // resultDesc = ' ';
            resultDesc = `${data.desc} (${data.normalLowerLimit != null ? data.normalLowerLimit : '无'} ~ ${data.normalUpperLimit != null ? data.normalUpperLimit : '无'})`;
          }
          emsEcmSpotRecords.push({ spotId: data.spotId, result, resultDesc });
        }
      });

      let result = '1';
      this.state.inpectResult.forEach(data => {
        if (data.checked) {
          result = data.value;
        }
      });
      const subData = {
        checkrecordId: this.props.navigation.state.params.checkrecordId,
        emsEcmSpotRecords,
        emsEcmCheckImages,
        equipmentId: this.state.equipmentId,
        remark: this.state.remark,
        result,
      };

      const data = await inspectionService.addEntry(subData);
      if (data) {
        UtilToast('处理成功', 'success');
        this.props.navigation.goBack();
        DeviceEventEmitter.emit('taskRerfesh');
        DeviceEventEmitter.emit('refreshTaskPageEvent');
        DeviceEventEmitter.emit('refreshPageEvent');
      }
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
    }
    DeviceEventEmitter.emit('showLoading', false);

    // const {
    //   sbid,
    //   sbdh,
    //   sblx,
    //   jjcd,
    //   wxbz,
    //   sbms,
    //   equipObjType,
    //   images,
    // } = this.state;
    // DeviceEventEmitter.emit('showLoading', true);
    // try {
    //   if (!this.failurePic && images.length > 0) {
    //     const imageResult = await todoService.uploadPic(images);
    //     this.failurePic = imageResult.data.fileId;
    //   }

    //   // const imageResult = await todoService.uploadPic(images);
    //   // if (this.failurePic) {
    //   let _jjcd = null;
    //   jjcd.forEach((it) => {
    //     if (it.checked) {
    //       _jjcd = it.value;
    //     }
    //   });
    //   let _sblx = null;
    //   sblx.forEach((it) => {
    //     if (it.checked) {
    //       _sblx = it.value;
    //     }
    //   });

    //   const mac = await DeviceInfo.getMACAddress().then();
    //   const carrier = DeviceInfo.getCarrier();
    //   const mobileModel = DeviceInfo.getModel();
    //   const { location } = await getCurrentPosition();
    //   const payload = {
    //     carrier,
    //     description: sbms,
    //     equipmentId: sbid,
    //     failureId: this.failureId,
    //     failureCode: sbdh,
    //     failureLevel: _jjcd,
    //     failureType: _sblx,
    //     latitude: location && location.coords && location.coords.latitude,
    //     longitude: location && location.coords && location.coords.longitude,
    //     equipObjType,
    //     mac,
    //     maintOrgId: wxbz.id,
    //     mobileModel,
    //     picture: this.failurePic,
    //     stepCode,
    //   };
    //   const result = await todoService.declareFailure(payload);
    //   if (result.success) {
    //     UtilToast('处理成功', 'success');
    //     this.props.navigation.goBack();
    //     DeviceEventEmitter.emit('refreshPageEvent');
    //   }
    //   // } else {
    //   //   UtilToast('图片上传失败', 'danger');
    //   // }
    // } catch (error) {
    //   DeviceEventEmitter.emit('showLoading', false);
    // }
    // DeviceEventEmitter.emit('showLoading', false);
  }

  onCheck = (index) => {
    this.setState(produce(draft => {
      draft.inspectItems[index].checked = !draft.inspectItems[index].checked;
    }));
  }

  choice = (index) => {
    this.setState(produce(draft => {
      draft.inspectItems[index].choice = !draft.inspectItems[index].choice;
    }));
  }

  choiceAll = () => {
    this.setState(produce(draft => {
      draft.inspectItems = draft.inspectItems.map(data => {
        data.choice = !draft.choiceAll;
        return data;
      });
      draft.choiceAll = !draft.choiceAll;
    }));
  }

  render() {
    return (
      <View style={{ flex: 1, flexDirection: 'column' }}>
        <ScrollView style={{ flex: 1, backgroundColor: theme.myPrimary }}>
          <View style={styles.container}>
            <View style={{ backgroundColor: 'rgba(255,255,255,0.2)', paddingTop: 4, paddingBottom: 4, borderRadius: 4 }}><FormText name="设备信息" /></View>
            <FormText name="编码" value={this.state.equipmentCode} />
            <FormText name="名称" value={this.state.equipmentName} />
            <View style={{ backgroundColor: 'rgba(255,255,255,0.2)', paddingTop: 4, paddingBottom: 4, borderRadius: 4, flexDirection: 'row', alignItems: 'center' }}>
              <View style={{ flex: 1 }}>
                <FormText name="巡检项" />
              </View>
              <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-end' }}>
                <TouchableWithoutFeedback onPress={() => this.choiceAll()}>
                  <Text style={{ color: this.state.choiceAll ? '#207aff' : 'white', marginRight: 8 }}>
                    全选
                  </Text>
                </TouchableWithoutFeedback>
              </View>
            </View>
            {
              this.state.inspectItems.map((data, index) => (
                <View style={{ padding: 8 }} key={index}>
                  {data.resultType == '0' && (
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                      <View style={{ flex: 2, alignItems: 'center' }}>
                        <TouchableWithoutFeedback onPress={() => this.choice(index)}>
                          <View style={{ flexDirection: 'row', flex: 1, alignItems: 'center' }}>
                            <ZlstIcon
                              style={{ color: data.choice ? '#207aff' : 'white', marginRight: 8 }}
                              name="gouxuan"
                              size={this.size}
                            />
                            <Text style={{ color: 'white', flex: 1 }}>
                              {data.splitItemDescription}
                            </Text>
                          </View>
                        </TouchableWithoutFeedback>
                      </View>
                      <View style={{ flex: 3, marginLeft: 8, flexDirection: 'column' }}>
                        <View style={{ flexDirection: 'row', flex: 1 }}>
                          <View style={{ flex: 1, flexWrap: 'wrap' }}>
                            <Text style={{ color: 'white' }}>
                              {data.inspection}
                            </Text>
                          </View>
                          <View style={{ flexDirection: 'row', flex: 1, justifyContent: 'flex-end', flexWrap: 'wrap' }}>
                            <Text onPress={() => this.onCheck(index)} style={[styles._button, { backgroundColor: data.checked ? '#207aff' : 'transparent', borderColor: data.checked ? '#207aff' : 'rgba(219,219,219,0.52)' }]}>
                              正常
                            </Text>
                            <Text onPress={() => this.onCheck(index)} style={[styles._button, { backgroundColor: !data.checked ? '#207aff' : 'transparent', borderColor: !data.checked ? '#207aff' : 'rgba(219,219,219,0.52)' }]}>
                              异常
                            </Text>
                          </View>
                        </View>
                        {!data.checked && (
                          <FormInput
                            placeholder="填写异常内容"
                            keyboardType="default"
                            value={this.state.inspectItems[index].desc}
                            _onChangeText={(text) => this.setState(produce(draft => {
                              draft.inspectItems[index].desc = text;
                            }))}
                          />
                        )}
                      </View>
                    </View>
                  )}
                  {data.resultType == '2' && (
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                      <View style={{ flex: 2, alignItems: 'center' }}>
                        <TouchableWithoutFeedback onPress={() => this.choice(index)}>
                          <View style={{ flexDirection: 'row', flex: 1, alignItems: 'center' }}>
                            <ZlstIcon
                              style={{ color: data.choice ? '#207aff' : 'white', marginRight: 8 }}
                              name="gouxuan"
                              size={this.size}
                            />
                            <Text style={{ color: 'white', flex: 1 }}>
                              {`${data.splitItemDescription}\n下限：${data.normalLowerLimit != null ? data.normalLowerLimit : '无'}\n上限：${data.normalUpperLimit != null ? data.normalUpperLimit : '无'}`}
                            </Text>
                          </View>
                        </TouchableWithoutFeedback>
                      </View>
                      <View style={{ flex: 3, marginLeft: 8, flexDirection: 'column', justifyContent: 'center' }}>
                        <FormInput
                          placeholder="填写内容"
                          keyboardType="numeric"
                          value={this.state.inspectItems[index].desc}
                          _onChangeText={(text) => this.setState(produce(draft => {
                            const newText = text.replace(/[^\d-.]+/, '');
                            draft.inspectItems[index].desc = newText;
                          }))}
                        />
                      </View>
                    </View>
                  )}
                </View>
              ))
            }
            <View style={{ backgroundColor: 'rgba(255,255,255,0.2)', paddingTop: 4, paddingBottom: 4, borderRadius: 4 }}><FormText name="巡检结果" /></View>
            <FormButtonRadio datas={this.state.inpectResult} _click={this.inpectResult} />
            <View style={{ backgroundColor: 'rgba(255,255,255,0.2)', paddingTop: 4, paddingBottom: 4, borderRadius: 4 }}><FormText name="备注" /></View>
            <FormTextarea
              value={this.state.remark}
              _onChangeText={(text) => this.setState({ remark: text })}
            />
            <View style={{ backgroundColor: 'rgba(255,255,255,0.2)', paddingTop: 4, paddingBottom: 4, borderRadius: 4 }}><FormText name="图片" /></View>
            <FormTakephoto
              datas={this.state.images}
              addImage={this.addImage}
              showBigImage={this.showBigImage}
              delImage={this.delImage}
            />
          </View>
        </ScrollView>
        <TouchableOpacity style={styles.footer} onPress={() => this.confirmSub()} activeOpacity={0.8}>
          <Image
            source={require('../../../../assets/images/btn-cut-line-xxx.png')}
            style={{ width: '100%', height: 2, alignItems: 'center' }}
            resizeMode="stretch"
            resizeMethod="auto"
          />
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text style={{ color: 'white' }}>提交</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme.myPrimary,
  },
  _button: {
    borderRadius: 2,
    textAlignVertical: 'center',
    padding: 5,
    margin: 5,
    color: 'white',
    textAlign: 'center',
    borderWidth: 1,
    borderStyle: 'solid',
  },
  footer: {
    width: '100%',
    flexDirection: 'column',
    backgroundColor: theme.myPrimary,
    height: 48,
  },
});

export default AddTaskDevice;
